package com.pixels.graphics;

import com.Math.Vector2D;
import com.Math.Polygon2D;

public class Drawer {
	int width;
	int height;
	int color;
	int[] pixels;

	public Drawer(int[] pixels, int width, int heigth) {
		this.pixels = pixels;
		this.height = heigth;
		this.width = width;
	}

	public void setColor(int c) {
		color = c;
	}

	public void clearFrame() {
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				pixels[x + (y * width)] = 0;
			}
		}
	}

	// Bresenham's circle algorithm
	public void sirkel3(int cx, int cy, int radius) {
		int error = -radius;
		int x = radius;
		int y = 0;

		while (x >= y) {
			plot8points(cx, cy, x, y);

			error += y;
			++y;
			error += y;

			if (error >= 0) {
				--x;
				error -= x;
				error -= x;
			}
		}
	}

	private void plot8points(int cx, int cy, int x, int y) {
		plot4points(cx, cy, x, y);
		if (x != y)
			plot4points(cx, cy, y, x);
	}

	private void plot4points(int cx, int cy, int x, int y) {
		setPixel(cx + x, cy + y);
		if (x != 0)
			setPixel(cx - x, cy + y);
		if (y != 0)
			setPixel(cx + x, cy - y);
		if (x != 0 && y != 0)
			setPixel(cx - x, cy - y);
	}

	public void setPixel(int x, int y) {
		int test = x + (y * width);
		if (test < pixels.length - 1 && test>=0 && x<=width && x>=0) {
			pixels[test] = color;
		} 
	}

	// Bresenham's line algorithm
	public void line(double x0, double y0, double x1, double y1) {
		line((int) x0, (int) y0, (int) x1, (int) y1);
	}

	public void line(Vector2D a, Vector2D b) {
		line((int) a.x, (int) a.y, (int) b.x, (int) b.y);
	}

	public void line(int x0, int y0, int x1, int y1) {
		int sx, sy;
		int dx = Math.abs(x1 - x0);
		int dy = Math.abs(y1 - y0);
		if (x0 < x1) {
			sx = 1;
		} else {
			sx = -1;
		}
		if (y0 < y1) {
			sy = 1;
		} else {
			sy = -1;
		}
		int err = dx - dy;

		while (true) {
			setPixel(x0, y0);
			if (x0 == x1 && y0 == y1) {
				break;
			}
			int e2 = 2 * err;
			if (e2 > -dy) {
				err = err - dy;
				x0 = x0 + sx;
			}
			if (e2 < dx) {
				err = err + dx;
				y0 = y0 + sy;
			}
		}
	}

	public void drawRect(int x, int y, int width, int height) {
		line(x, y, x + width, y);
		line(x, y, x, y + height);
		line(x + width, y, x + width, y + height);
		line(x, y + height, x + width, y + height);
	}

	// tegner polygoner med linjer fra sentrum
	public void drawPoly(Polygon2D p) {
		for (int i = 0; i < p.verts.length - 1; i++) {
			line(Vector2D.add(p.verts[i], p.center), Vector2D.add(p.verts[i + 1], p.center));
		}
		line(Vector2D.add(p.verts[p.verts.length - 1], p.center), Vector2D.add(p.verts[0], p.center));
		//tegner linjer mellom senter og alle kantene
		 // for (int i = 0; i < p.verts.length; i++) { line(p.center,
		  //Vector2D.add(p.verts[i], p.center)); }
		 
	}
}
